﻿<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@include file="/common/global.jsp" %>
<!--_meta 作为公共模版分离出去-->
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta name="renderer" content="webkit|ie-comp|ie-stand">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<link rel="Bookmark" href="/favicon.ico" >
<link rel="Shortcut Icon" href="/favicon.ico" />
	<%@include file="/common/head.jsp"%>
<!--/meta 作为公共模版分离出去-->

<title>新建网站角色 - 管理员管理 - H-ui.admin v3.0</title>
<meta name="keywords" content="H-ui.admin v3.0,H-ui网站后台模版,后台模版下载,后台管理系统模版,HTML后台模版下载">
<meta name="description" content="H-ui.admin v3.0，是一款由国人开发的轻量级扁平化网站后台模板，完全免费开源的网站后台管理系统模版，适合中小型CMS后台系统。">

<script src="${staticPath}/static/frontend/libs/vue.min.js"></script>
</head>
<body>
<article class="page-container">
	<form action="" method="post" class="form form-horizontal" id="form-admin-role-add">

	 <div id="app">
		 <div class="row cl">
			 <div v-show="showList" class="formControls col-xs-8 col-sm-9">
				<%-- roleName:{{ roleName }}<br>
				 role:{{ role }}<br>--%>
				 <%--memberId:{{ memberId }}<br>--%>
					<%--${loginUser}--%>
			 </div>
		 </div>
		<div class="row cl">
			<label class="form-label col-xs-4 col-sm-3"><span class="c-red">*</span>角色名称：</label>
			<div class="formControls col-xs-8 col-sm-9">
				<input type="text" class="input-text" value="" placeholder="" id="roleName" name="roleName" v-model="role.roleName">
			</div>
		</div>
		<div class="row cl">
			<label class="form-label col-xs-4 col-sm-3"><span class="c-red">*</span>角色编号：</label>
			<div class="formControls col-xs-8 col-sm-9">
				<input type="text" class="input-text" value="" placeholder="" id="roleCode" name="roleName" v-model="role.roleCode">
			</div>
		</div>


		 <c:if test="${loginUser.type eq 'admin'}">
		 <div class="row cl">
			 <label class="form-label col-xs-4 col-sm-3"><span class="c-red">*</span>所属机构：</label>
			 <div class="formControls col-xs-8 col-sm-9">
				 <input type="text" class="input-text" style="cursor:pointer;" v-model="role.orgName" name="orgName" @click="deptTree" readonly="readonly" placeholder="所属机构"/>
			 </div>
		 </div>
		 </c:if>

		 <c:if test="${loginUser.type eq 'busi'}">
		 <div class="row cl">
			 <label class="form-label col-xs-4 col-sm-3"><span class="c-red">*</span>所属商户：</label>
			 <div class="formControls col-xs-8 col-sm-9">
				 <select id="member" name="memberId" v-model="role.memberId"></select><%--TODO: vue是双向绑定不了select--%>
			 </div>
		 </div>
		 </c:if>
		<div class="row cl">
			<label class="form-label col-xs-4 col-sm-3">备注：</label>
			<div class="formControls col-xs-8 col-sm-9">
				<input type="text" class="input-text" value="" placeholder="" id="" name="" v-model="role.roleDesc">
			</div>
		</div>
		<div class="row cl">
			<label class="form-label col-xs-4 col-sm-3">功能权限:</label>
			<div class="form-inline clearfix" style="margin-top:30px;margin-left:26px;">
				<div class="form-group col-md-3">
					<strong class="col-sm-5 control-label">功能权限</strong>
					<div class="col-sm-10">
						<ul id="menuTree" class="ztree"></ul>
					</div>
				</div>
			</div>
		</div>
		<div class="row cl">
			<div class="col-xs-8 col-sm-9 col-xs-offset-4 col-sm-offset-3">
				<button type="submit" class="btn btn-success radius" id="admin-role-save" name="admin-role-save"><i class="icon-ok"></i> 确定</button>
			</div>
		</div>
	</div>
	</form>

</article>
<!-- 选择商户 -->
<div id="deptLayer" style="display: none;padding:10px;">
	<ul id="deptTree" class="ztree"></ul>
</div>
<!--_footer 作为公共模版分离出去-->
<%@include file="/common/footer.jsp"%>
<%@include file="/common/tooltip.jsp"%>
<!--请在下方写此页面业务相关的脚本-->
<%@include file="/common/validation.jsp"%>
<!--/请在上方写此页面业务相关的脚本-->
<script>
    /**
	 * author:Dante Fung
	 * date:2017-8-24 23:52:26
     * @type {string}
     */
	///////////////////////////////////Global Variable Declared ////////////////////////
	var baseURL = '${basePath}/';

	//////////////////////////////////Setting start ////////////////////////////////////
    // 资源菜单树
    var menu_ztree;
    var menu_setting = {
        data: {
            simpleData: {
                enable: true,
                idKey: "id",
                pIdKey: "parentId",
                rootPId: -1
            },
            key: {
                url:"nourl",
				name:"resourceName"
            }
        },
        check:{
            enable:true, // 启用勾选checkbox
            nocheckInherit:true
        }
    };

    // 部门结构树
    var dept_ztree;
    var dept_setting = {
        data: {
            simpleData: {
                enable: true,
                idKey: "id",
                pIdKey: "parentId",
                rootPId: -1
            },
            key: {
                url:"nourl",
				name:"orgName"
            }
        }
    };

    //////////////////////////////////Setting end ////////////////////////////////////

/////////////////////////////////////// vue inital start ..///////////////////////////
    var vm = new Vue({
        el:'#app',
        data:{
            q:{
                roleName: null
            },
            showList: true,
            title:null,
            role:{
                id:null,        // 角色ID
                roleName:null,  // 角色名称
                orgName:null,   // 组织机构名称
                orgId:null,    // 组织机构ID
                memberId:null,  // 商户ID
                roleCode:null,  // 角色编号
                roleDesc:null  // 角色描述
            }
        },
        methods: {
            query: function () {
                vm.reload();
            },
            getRole: function(roleId){
                $.get(baseURL + "sys/role/list?id="+roleId, function(r){
                    vm.role = r.role;

                    //勾选角色所拥有的菜单
                    var menuIds = vm.role.menuIdList;
                    for(var i=0; i<menuIds.length; i++) {
                        var node = menu_ztree.getNodeByParam("menuId", menuIds[i]);
                        menu_ztree.checkNode(node, true, false);
                    }

                    //勾选角色所拥有的部门数据权限
                    var deptIds = vm.role.deptIdList;
                    for(var i=0; i<deptIds.length; i++) {
                        var node = data_ztree.getNodeByParam("deptId", deptIds[i]);
                        data_ztree.checkNode(node, true, false);
                    }

                    vm.getDept();
                });
            },
            saveOrUpdate: function () {
                //获取选择的菜单
                var nodes = menu_ztree.getCheckedNodes(true);
                var menuIdList = new Array();
                for(var i=0; i<nodes.length; i++) {
                    menuIdList.push(nodes[i].id);
                }
                vm.role.permissionIds = menuIdList;

                logger.info({groupName:'---------我就像看看即将提交到后台的vue的model最终长啥样了----------', data:vm.role});
                var url = vm.role.roleId == null ? "sys/role/save" : "sys/role/update";
                $.ajax({
                    type: "POST",
                    url: baseURL + url,
                    contentType: "application/json",
					dataType:'JSON',
                    data: JSON.stringify(vm.role),
                    success: function(data){
                        logger.info({groupName:'-------------我正在执行保存操作--------------',data:data});
                        if(data.status === '200'){
                            layer.confirm('操作成功', {icon:1, btn:['确认']},function(){
                                vm.reload();
                            });
                        }else{
                            alert(data.msg);
                        }
                    },
					error:function(msg) {
						logger.info(msg);
					}

                });
            },
            getMenuTree: function(roleId) {
                //加载菜单树
				$.ajax({
					url:'${basePath}/sys/permission/list',
					type:'POST',
					dataType:'JSON',
					success:function(r){
                        logger.info({groupName:'-------------加载菜单树---------', data:r});
                        menu_ztree = $.fn.zTree.init($("#menuTree"), menu_setting, r);
                        //展开所有节点
                        menu_ztree.expandAll(true);

                        if(roleId != null){
                            vm.getRole(roleId); // 勾选角色所拥有的资源
                        }
					},
					error:function(msg) {
						logger.info(msg);
					}
				});
            },
            getDept: function(){
                //加载部门树
                $.ajax({
                    url:"${basePath}/sys/dept/list",
                    type:'POST',
                    dataType:'JSON',
                    success:function(r){
                        logger.info({groupName:'-------------加载机构树---------', data:r});
                        dept_ztree = $.fn.zTree.init($("#deptTree"), dept_setting, r);
                    },
                    error:function(msg) {
                        logger.info(msg);
                    }
                });
            },
            deptTree: function(){
                layer.open({
                    type: 1,
                    offset: '50px',
                    skin: 'layui-layer-molv',
                    title: "选择部门",
                    area: ['300px', '450px'],
                    shade: 0,
                    shadeClose: false,
                    content: jQuery("#deptLayer"),
                    btn: ['确定', '取消'],
                    btn1: function (index) {
                        var node = dept_ztree.getSelectedNodes();
                        logger.info({groupName:'-------------选择部门|就想看看当前选中的node长啥样子------------',data:node});
                        //选择上级部门
                        vm.role.orgId = node[0].id;
                        vm.role.orgName = node[0].orgName;
                        logger.info({groupName:'-------------就想看看当前Vue的Model的变化------------',data:vm.role});

                        layer.close(index);
                    }
                });
            },
			loadMemberData: function() {
                $('#member').select2({
					placeholder: '至少选择一个',
						//allowClear: true,
						width: '100%',
						ajax: {
						url: '${basePath}/member/loadSelectData',
							data: function(term, page) { // 请求参数（GET）
							return {
								q: term.term
							};
						},
						dataType: 'json',
						cache: true,
						processResults: function (data) {
							return {results: data.options};
						}
					}
            });
			},
            reload: function () {
                window.location.href = '${basePath}/sys/role/list';
                var index = parent.layer.getFrameIndex(window.name);
                parent.layer.close(index);
            }
        }
});

/////////////////////////////////////// vue inital end ..///////////////////////////

//////////////////////////////////////init some plugins start //////////////////////
(function(global){
    // 初始化菜单树
    global.vm.getMenuTree(null);
    // 初始化部门树
	global.vm.getDept();
    // 启用select2框:商户
    global.vm.loadMemberData();
})(this);
    //////////////////////////////////////init some plugins end //////////////////////

///////////////////////////////////页面加载时执行///////////////////////////////////
$(function(){
	$("#form-admin-role-add").validate({
		rules:{
			roleName:{
				required:true
			},
		},
		onkeyup:false,
		focusCleanup:true,
		success:"valid",
		submitHandler:function(form){
			// TODO : 执行vue的saveOrUpdate方法.
			vm.saveOrUpdate();
		}
	});
});
</script>

</body>
</html>